const DB = require('../db')

async function update(status) {
    let one = await DB.Status.findOne();
    if (!one) {
        return await new DB.Status(status).save();
    }
    return DB.Status.updateOne({
        _id: status._id
    }, {
        interval: status.interval,
        crawlerStatus: status.crawlerStatus
    });
}

async function query() {
    let status = await DB.Status.findOne();
    let emailCount = await DB.Email.countDocuments({
        state: 1
    });
    let keywordCount = await DB.Keyword.countDocuments({
        state: 1
    });
    let siteCount = await DB.Site.countDocuments({
        state: 1
    });
    if (!status) {
        status = {
            crawlerStatus: 0,
            interval: 30,
            crawlerLastStopTime: new Date()
        }
    }
    status.siteCount = siteCount;
    status.keywordCount = keywordCount;
    status.emailCount = emailCount;
    update(status);
    return status;
}

async function updateCrawlerState(state) {
    if (state === 0) {
        return DB.Status.updateOne({}, { crawlerLastStopTime: new Date(), crawlerStatus: state });
    }
    return DB.Status.updateOne({}, { crawlerStatus: state });
}

module.exports = {
    update,
    query,
    updateCrawlerState
}